"""

    异步操作Postgresql

"""

import asyncpg
import asyncio
from random import sample, randint


def load_common_words():
    with open('common_words.txt', 'r', encoding='utf-8') as f:
        return f.readlines()


def generate_brand_names(words):
    return [(words[index][:-2],) for index in sample(range(100), 100)]


async def insert_brands(common_words, connection):
    brands = generate_brand_names(common_words)
    print(brands)
    insert_brands = "insert into brand values (DEFAULT, $1);"
    return await connection.executemany(insert_brands, brands)


def gen_products(common_words, brand_id_start, brand_id_end, products_to_create):
    products = []
    for _ in range(products_to_create):
        description = [common_words[index][:-2] for index in sample(range(1000), 10)]
        brand_id = randint(brand_id_start, brand_id_end)
        products.append(("".join(description), brand_id))
        print((" ".join(description), brand_id))
    return products


def gen_skus(product_id_start, product_id_end, skus_to_create):
    skus = []
    for _ in range(skus_to_create):
        product_id = randint(product_id_start, product_id_end)
        size_id = randint(1, 3)
        color_id = randint(1, 2)
        skus.append((product_id, size_id, color_id))
    return skus


async def main():
    common_words = load_common_words()
    connection = await asyncpg.connect(
        host="127.0.0.1",
        port="5432",
        database="products",
        user="around",
        password="zhouwei",
    )
    await insert_brands(common_words, connection)
    product_tuples = gen_products(common_words, 1, 100, 1000)
    await connection.executemany("insert into product values (DEFAULT, $1, $2)", product_tuples)
    skus_tuples = gen_skus(1, 1000, 100000)
    await connection.executemany("insert into sku values (DEFAULT, $1, $2, $3)", skus_tuples)
    await connection.close()


asyncio.run(main())
